package my.zuul.demo.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class UserFilter extends ZuulFilter {
    /**
     * nginx代理相对应请求路径，然后转发到对应的zuul服务
     * upstram userzuul{
     *     server 127.0.0.1:8901;
     *     #↓假如有多个zuul服务↓
     *     server 127.0.0.1:8902;
     * }
     * server{
     *     listen 80;
     *     location /user {
     *         proxy_pass http://userzuul;
     *         proxy_set_header Host $host:8901:
     *     }
     * }
     */

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getParameter("token");
        if (StringUtils.isEmpty(token)) {
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(401);
            currentContext.setResponseBody("token is empty");
            return null;
        }
        return null;
    }


}
